package com.eds.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eds.exception.BusException;
import com.eds.feign.UserService;
import com.eds.mapper.NotificationMapper;
import com.eds.mapper.UserNotificationMapper;
import com.eds.pojo.CodeEnum;
import com.eds.service.NotificationService;
import com.pojo.Notification;
import com.pojo.UserNotification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 34195
 * @description 针对表【notification(通知主表)】的数据库操作Service实现
 * @createDate 2025-04-07 16:20:11
 */
@Service
public class NotificationServiceImpl extends ServiceImpl<NotificationMapper, Notification>
        implements NotificationService {

    @Autowired
    private NotificationMapper notificationMapper;

    @Autowired
    private UserNotificationMapper userNotificationMapper;
    @Autowired
    private UserService userService;

    /* *
     * @Title: getUserNotificationList
     * @Author: vvSmile
     * @Date: 2025-04-08 11:01:22
     * @param userId
     * @param noticeType
     * @return List<Notification>
     * @Description: TODO 获取通知列表
     */
    @Override
    public List<Notification> getUserNotificationList(String token, String noticeType) {
        //根据token获取userId
        Long userId = userService.getUserIdFromToken(token);
        if (userId == 0) {
            throw new BusException(CodeEnum.GET_USERID_BY_TOKEN.getCode(), CodeEnum.GET_USERID_BY_TOKEN.getMessage());
        }
        QueryWrapper<UserNotification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("notification_type", noticeType);
        List<UserNotification> userNotifications = userNotificationMapper.selectList(queryWrapper);
        ArrayList<Notification> notifications = new ArrayList<>();
        userNotifications.forEach(userNotification -> {
            QueryWrapper<Notification> notificationQueryWrapper = new QueryWrapper<>();
            notificationQueryWrapper.eq("notification_id", userNotification.getNotificationId())
                    .and(wrapper -> wrapper.eq("status", 0).or().eq("status", 1));

            Notification notification = notificationMapper.selectOne(notificationQueryWrapper);
            notifications.add(notification);
        });
        return notifications;
    }

    /* *
     * @Title: saveNotification
     * @Author: vvSmile
     * @Date: 2025-04-08 11:01:07
     * @param notification
     * @Description: TODO 保存通知
     */
    @Override
    @Transactional
    public Boolean saveNotification(Notification notification) {
        int insert = notificationMapper.insert(notification);
        //建立通知-用户关联关系
        if (notification.getSenderId() != null) {
            UserNotification userNotification = new UserNotification();
            userNotification.setUserId(notification.getSenderId());
            userNotification.setNotificationId(notification.getNotificationId());
            userNotification.setIsRead(0);
            userNotification.setNotificationType(notification.getNoticeType());
            userNotification.setCreateTime(new Date());
            userNotification.setUpdateTime(new Date());
            int insert1 = userNotificationMapper.insert(userNotification);
        }
        return insert > 0;
    }


    /* *
     * @Title: getUnreadNotification
     * @Author: vvSmile
     * @Date: 2025-04-08 10:58:07
     * @param userId
     * @param noticeType
     * @return Integer
     * @Description: TODO 获取未读消息数量
     */
    @Override
    public Integer getUnreadNotification(String token, String noticeType) {
        //根据token获取userId
        Long userId = userService.getUserIdFromToken(token);
        if (userId == 0) {
            throw new BusException(CodeEnum.GET_USERID_BY_TOKEN.getCode(), CodeEnum.GET_USERID_BY_TOKEN.getMessage());
        }
        QueryWrapper<UserNotification> queryWrapper = new QueryWrapper<UserNotification>()
                .eq("user_id", userId)
                .eq("notification_type", noticeType)
                .eq("is_read", 0)
                .eq("del_flag", 0);
        if (userNotificationMapper.selectCount(queryWrapper) > 0) {
            return userNotificationMapper.selectCount(queryWrapper);
        }
        return null;
    }


    /* *
     * @Title: readNotification
     * @Author: vvSmile
     * @Date: 2025-04-08 11:01:55
     * @param userId
     * @param noticeType
     * @return boolean
     * @Description: TODO 读通知
     */
    @Override
    public boolean readNotification(String token, Long notificationId) {
        //根据token获取userId
        Long userId = userService.getUserIdFromToken(token);
        if (userId == 0) {
            throw new BusException(CodeEnum.GET_USERID_BY_TOKEN.getCode(), CodeEnum.GET_USERID_BY_TOKEN.getMessage());
        }
        //更新通知-用户关联关系
        UpdateWrapper<UserNotification> userNotificationUpdateWrapper = new UpdateWrapper<>();
        userNotificationUpdateWrapper.eq("user_id", userId)
                .eq("notification_id", notificationId)
                .set("is_read", 1)
                .set("read_time", new Date());
        //更新通知表
        UpdateWrapper<Notification> notificationUpdateWrapper = new UpdateWrapper<>();
        notificationUpdateWrapper.eq("notification_id", notificationId)
                .set("status", 1)
                .set("update_time", new Date());
        int updateUserNotification = userNotificationMapper.update(null, userNotificationUpdateWrapper);
        int updateNotification = notificationMapper.update(null, notificationUpdateWrapper);
        if (updateUserNotification > 0 && updateNotification > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteNotificationById(String token, Long notificationId) {
        //根据token获取userId
        Long userId = userService.getUserIdFromToken(token);
        if (userId == 0) {
            throw new BusException(CodeEnum.GET_USERID_BY_TOKEN.getCode(), CodeEnum.GET_USERID_BY_TOKEN.getMessage());
        }
        //查询用户是否拥有该通知
        QueryWrapper<UserNotification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("notification_id", notificationId);
        UserNotification userNotification = userNotificationMapper.selectOne(queryWrapper);
        if (userNotification != null) {
            //删除通知
            UpdateWrapper<Notification> notificationUpdateWrapper = new UpdateWrapper<>();
            notificationUpdateWrapper.eq("notification_id", notificationId)
                    .set("status", -1);
            int deleteNotification = notificationMapper.update(null, notificationUpdateWrapper);
            //删除通知用户关联
            UpdateWrapper<UserNotification> userNotificationUpdateWrapper = new UpdateWrapper<>();
            userNotificationUpdateWrapper.eq("user_id", userId)
                    .eq("notification_id", notificationId)
                    .set("del_flag", 1);
            int deleteUserNotification = userNotificationMapper.update(null, userNotificationUpdateWrapper);
            if (deleteNotification > 0 && deleteUserNotification > 0) {
                return true;
            }
        }
        return false;
    }
}




